// miniprogram/pages/find/index.js
const app = getApp();
var util = require('../../utils/util.js')
var userInfo, shang_height = 0;
var that;

function compare(val) {
  return function (a, b) {
    var value1 = a[val];
    var value2 = b[val];
    var val3 = value1 - value2;
    return val3;
  }
}
Page({
  data: {
    list: [],
    showModal:false,
    loginStatus: 0, //0 未知  1 已登录  2 未登录
    my_user: {}
  },
  onLoad(){
    console.log('aaaaaaaa',getApp().openid)
  },
  //用户授权登录登录
  loginGetUserInfo: function (e) {
    console.log('aaaaa',e)
    var that = this;
    let iv = e.detail.iv
    if (e.detail.iv == undefined) { //如果用户拒绝授权
    } else {
      wx.getUserInfo({ //调用授权api，获取用户信息
        success: function (res) {
          var userInfo = res.userInfo
          wx.cloud.callFunction({
            name: "openId",
            data: {},
            success(res) {
              var openid = res.result.openid;
              userInfo.openid = openid;

              app.DB.collection('user').get({
                  success: function (res) {
                    console.log('=============>', res.data)
                    var is_my =false;
                    res.data.forEach(item=>{
                      if(item._openid == openid){
                        is_my=item
                      }
                    })
                    if (is_my&&is_my.userInfoDetail.nicheng) {
                      wx.setStorageSync('userInfo', is_my)
                      wx.reLaunch({
                        url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                      })
                    }else if (is_my&&!is_my.userInfoDetail.nicheng) {
                      wx.setStorageSync('userInfo', is_my)
                      wx.reLaunch({
                        url: '/pages/info/index?nav_type=login' // 这里是要跳转的路径
                      })
                    } else {
                      userInfo.userInfoDetail = {};
                      userInfo.id_num = 6230001+ res.data.length;
                      userInfo.seeNum=0
                      userInfo.tiwenNum=0
                      userInfo.zan_openid=[]
                      console.log('-------',userInfo.id_num,res.data.length)
                      app.DB.collection('user').add({
                        data: userInfo,
                        success: function (res) {
                          console.log('添加用户', res)
                          userInfo._id = res._id;
                          wx.setStorageSync('userInfo', userInfo)
                          wx.reLaunch({
                            url: '/pages/info/index?nav_type=login' // 这里是要跳转的路径
                          })
                        }
                      })
                    }
                  }
                })
            },
            fail(res) {
              console.log('333333333失败', res)
            }
          })
        }
      })
    }
  },

  nav_detail(e) {
    console.log(e)

    // 已登录
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').userInfoDetail && wx.getStorageSync('userInfo').userInfoDetail.live_phone) {} else {
      wx.showModal({
        title: '温馨提示',
        content: '请先填写交友信息，才可以查看他人信息',
        showCancel: true,
        success: (result) => {
          if (result.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/info/index?nav_type=login' // 这里是要跳转的路径
            })
          } else if (result.cancel) {
            console.log('用户点击取消')
          }
        },
      })
      return
    }
    let userInfo = e.currentTarget.dataset.userinfo;
    var see_list = wx.getStorageSync('see_list') || [];
    var seeuserInfo_list = wx.getStorageSync('seeuserInfo_list') || [];

    if (see_list.indexOf(userInfo._openid) != -1) {} else {
      see_list.push(userInfo._openid)
      seeuserInfo_list.push(userInfo)
    }

    console.log('00000000', see_list)
    wx.setStorageSync('see_list', see_list)
    wx.setStorageSync('seeuserInfo_list', seeuserInfo_list)
    wx.setStorageSync('seeuserInfo', userInfo)
    wx.navigateTo({
      url: '/pages/user_detail/user_detail',
    })
  },
   
  showCancelOrder: function() {
    this.setData({
      showModal:true
    })
  },
  // 确定
  Sure: function () {
    console.log('用户点击确定')
    let sex = '男';
    that.getData(2, sex)
    wx.setStorageSync('sex', sex)
    that.setData({
      renqi: 0,
      showModal: false,
      loginStatus: 2
    })
  },
  modal_click_Hidden: function(e) {
    console.log('用户点击取消')
    let sex = '女';
    that.getData(2, sex)
    wx.setStorageSync('sex', sex)
    that.setData({
      renqi: 0,
      showModal: false,
      loginStatus: 2
    })
  },
  cancelOrder: function() {
    
  },
  nav_info(){
    wx.navigateTo({
      url: '/pages/info/index',
    })
  },
  onShow: function () {
    that = this;
    // this.se_sex()
    if (wx.getStorageSync('share_id')) {
      app.DB.collection('user').doc(wx.getStorageSync('share_id')).get().then(res => {
        console.log('res', res.data)
        wx.setStorageSync('seeuserInfo', res.data)
        wx.setStorageSync('share_id', false)
        wx.navigateTo({
          url: '/pages/user_detail/user_detail',
        })
      })
      return
    }
    this.setData({
      aaaa: "",
      bbbb: "",
      cccc: "",
      dddd: "",
      eeee: "",
      ffff: "",
      my_user: wx.getStorageSync('userInfo').userInfoDetail
    })
    this.show_hongdian()
    // 已登录
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').userInfoDetail && wx.getStorageSync('userInfo').userInfoDetail.live_phone) {
      this.getData(1)
      app.DB.collection('user').doc(wx.getStorageSync('userInfo')._id).get().then(res => {
        console.log('res', res.data)
        var tiwenNum = res.data.tiwenNum;
        var seeNum = res.data.seeNum;
        var zan_openid = res.data.zan_openid ? res.data.zan_openid.length : 0;
        var renqi = tiwenNum + seeNum + zan_openid;

        this.setData({
          renqi,
          loginStatus: 1
        })
      })
    } else {
      wx.cloud.callFunction({
        name: "openId",
        data: {},
        success(res) {
          console.log('个人信息-------------',res.result.openid)
          app.DB.collection('user').where({
            _openid: res.result.openid
          })
          .get().then(ress => {
            wx.setStorageSync('userInfo', ress.data[0])
            if (wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').userInfoDetail && wx.getStorageSync('userInfo').userInfoDetail.live_phone) {
              that.getData(1)
              app.DB.collection('user').doc(wx.getStorageSync('userInfo')._id).get().then(res => {
                console.log('res', res.data)
                var tiwenNum = res.data.tiwenNum;
                var seeNum = res.data.seeNum;
                var zan_openid = res.data.zan_openid ? res.data.zan_openid.length : 0;
                var renqi = tiwenNum + seeNum + zan_openid;
        
                that.setData({
                  renqi,
                  loginStatus: 1
                })
              })
            }else{
              that.se_sex()
            }
          })
        }
      })
    }
  },
  
  getMyInfo(_openid){
    app.DB.collection('user').where({
      _openid: _openid
    })
    .get().then(ress => {
      console.log('onShow',_openid, ress)
      wx.setStorageSync('userInfo', ress.data[0])
        if(!ress.data[0].userInfoDetail||!ress.data[0].userInfoDetail.sex){
          this.se_sex()
          return
        }
        wx.setStorageSync('sex',ress.data[0].userInfoDetail.sex)
        this.getData(1)
        console.log('res', ress.data)
        var tiwenNum =ress.data[0].tiwenNum;
        var seeNum =ress.data[0].seeNum;
        var zan_openid =ress.data[0].zan_openid?ress.data[0].zan_openid.length:0;
        var renqi = tiwenNum+seeNum+zan_openid;
  
      if(getApp().guanli_list_openid.indexOf(ress.data[0]._openid)!=-1){
        this.setData({
          guanli:true
        })
      }else{
        this.setData({
          guanli:false
        })
      }
      this.setData({
        loginStatus: 1,
        userInfo:ress.data[0],
        renqi
      })
    })
  },
  se_sex(){
    if(wx.getStorageSync('sex')){
      that.getData(2,wx.getStorageSync('sex'))
      that.setData({
        renqi: 0,
        loginStatus: 2
      })
      return
    }
    console.log('---------------')
    this.setData({
      showModal:true
    })
  },
  getData(type, sex) {
    var see_list = wx.getStorageSync('see_list') || [];
    wx.cloud.callFunction({
      name: 'get_user', // 对应云函数名
      data: {},
      success: res => {
        console.log('有城列表', res.result.data)
        var list = res.result.data;

        if (type == 2) {
          //  未登录 
          list.forEach((item, idx) => {
            // console.log('item', item.userInfoDetail.nicheng,item.nickName,idx)
            item.fen = 100;
            item.renqi = (item.tiwenNum || 0) + (item.seeNum || 0) + ((item.zan_openid && item.zan_openid.length) || 0);
            let seeIdx = see_list.indexOf(item._openid);
            console.log('数据对比1111111', seeIdx)
            try {

              if (seeIdx != -1) {
                console.log('数据对比0-------', util.deepEqual(item.userInfoDetail, wx.getStorageSync('seeuserInfo_list')[seeIdx].userInfoDetail), item.userInfoDetail, wx.getStorageSync('seeuserInfo_list')[seeIdx].userInfoDetail)
                if (util.deepEqual(item.userInfoDetail, wx.getStorageSync('seeuserInfo_list')[seeIdx].userInfoDetail)) {
                  item.seeStatus = 2
                } else {
                  item.seeStatus = 1
                }
              } else {
                item.seeStatus = 0
              }
            } catch (error) {
              console.log(error)
            }
          })

          list = list.filter(item => item.userInfoDetail.sex != sex);
          list.sort(compare('renqi')).sort(compare('fen')).reverse();
          that.set_vv_data(list)
          that.setData({
            yuan_list: list,
            _openid: wx.getStorageSync('userInfo')._openid
          })
          return
        }

        let fen = 0;
        var listArr = []
        // console.log('list', list.length)
        var list_length = 0;
        list.forEach((item, idx) => {
          // console.log('item', item.userInfoDetail.nicheng,item.nickName,idx)
          item.fen = 0;
          item.renqi = (item.tiwenNum || 0) + (item.seeNum || 0) + ((item.zan_openid && item.zan_openid.length) || 0);

          try {
            let seeIdx = see_list.indexOf(item._openid);
            // console.log('数据对比0-------', seeIdx)
            if (seeIdx != -1) {
              if (util.deepEqual(item.userInfoDetail, wx.getStorageSync('seeuserInfo_list')[seeIdx].userInfoDetail)) {
                // console.log('数据对比1111111')
                item.seeStatus = 1
              } else {
                item.seeStatus = 2
                // console.log('数据对比222222222')
              }
            } else {
              item.seeStatus = 0
            }
          } catch (error) {
            console.log(error)
          }
          if (item.character_list) {
            for (var itt in item.character_list) {
              if (item.character_list[itt] == wx.getStorageSync('userInfo').character_list[itt]) {
                item.fen = (item.fen + 5) || 5
              }
            }
          }

          if (item.user_status && item.userInfoDetail && item.userInfoDetail.sex != wx.getStorageSync('userInfo').userInfoDetail.sex && item.userInfoDetail.nicheng && item.openid != wx.getStorageSync('userInfo').openid) {
            listArr.push(item)
          }

        })

        listArr.sort(compare('renqi')).sort(compare('fen')).reverse();
        // list.sort(compare2('renqi')).reverse();
        console.log('list22', listArr)
        that.set_vv_data(listArr)
        that.setData({
          yuan_list: listArr,
          _openid: wx.getStorageSync('userInfo').openid
        })
      }
    })
  },
  show_hongdian() {
    if (!wx.getStorageSync('userInfo')) return
    const _ = app.DB.command;
    // liaotian中，显示小红点
    var _openid = wx.getStorageSync('userInfo')._openid
    app.DB.collection('friends').where(_.or([{
          a: _.eq(_openid)
        },
        {
          b: _.eq(_openid)
        }
      ]))
      .get({
        success: function (res) {
          // console.log('——————————————————————————>', res.data)
          res.data.forEach(item => {
            if (item.a == _openid && item.a_hongdian == true) {
              console.log('我是A')
              wx.showTabBarRedDot({
                index: 2
              })
            }
            if (item.b == _openid && item.b_hongdian == true) {
              console.log('我是B')
              wx.showTabBarRedDot({
                index: 2
              })
            }
          })
        }
      })

    // 【我的】-【邀请记录】-【邀请我的】中，有未处理的邀请记录，就在【邀请记录】上显示小红点
    app.DB.collection('invitation_list').where({
        b: _openid,
      })
      .get().then(ress => {
        ress.data.forEach(item => {
          if (item.status != 1 && item.status != 2) {
            wx.showTabBarRedDot({
              index: 3
            })
          }
        })
      })
  },
  set_vv_data(list) {
    if (list.length == 0) {
      console.log('------00000000', list)
      // list = that.data.yuan_list
    }
    console.log('list', list)
    var vList = [];
    var v2List = [];
    for (var i = 0; i < list.length; i++) {
      // console.log('------2222',list[i].nickName,list[i].userInfoDetail.live_phone.length)
      if (vList.length <= v2List.length) {
        if (list[i].userInfoDetail && list[i].userInfoDetail.live_phone && list[i].userInfoDetail.live_phone.length > 0) vList.push(list[i])
      } else {
        if (list[i].userInfoDetail && list[i].userInfoDetail.live_phone && list[i].userInfoDetail.live_phone.length > 0) v2List.push(list[i])
      }
    }
    // console.log('------1111111', vList,v2List)
    that.setData({
      vList,
      v2List,
    })
    setTimeout(() => {
      that.setData({
        listShow: true
      })
    }, 1500);
  },
  //年龄段
  aaaa() {
    if (!wx.getStorageSync('userInfo') || !wx.getStorageSync('userInfo').userInfoDetail || !wx.getStorageSync('userInfo').userInfoDetail.nicheng) {
      wx.showToast({
        title: '未填写信息，无法筛选',
        icon: 'none'
      })
      return
    }
    let liss = ['都可以', '相差5岁以内', '比我大', '比我小']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];
        try {
          
        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {
          list.forEach(item => {
            let myAge = util.ages(that.data.my_user.age)||util.ages(that.data.my_user.age+"-01")
            let itemAge = util.ages(item.userInfoDetail.age)||util.ages(item.userInfoDetail.age+"-01")
            console.log('22222',myAge,itemAge,(myAge - itemAge <= 5 && myAge - itemAge >= -5),item.userInfoDetail.nicheng)

            if (item.userInfoDetail && item.userInfoDetail.age && (myAge - itemAge <= 5 && myAge - itemAge >= -5)) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            let myAge = util.ages(that.data.my_user.age)||util.ages(that.data.my_user.age+"-01")
            let itemAge = util.ages(item.userInfoDetail.age)||util.ages(item.userInfoDetail.age+"-01")

            if (item.userInfoDetail && item.userInfoDetail.age && itemAge > myAge) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 3) {
          list.forEach(item => {
            let myAge = util.ages(that.data.my_user.age)||util.ages(that.data.my_user.age+"-01")
            let itemAge = util.ages(item.userInfoDetail.age)||util.ages(item.userInfoDetail.age+"-01")
            console.log('-----',util.ages(item.userInfoDetail.age),util.ages(that.data.my_user.age))
            if (item.userInfoDetail && item.userInfoDetail.age && itemAge <  myAge) {
              arr.push(item)
            }
          })
        }
      } catch (error) {
        
      }
        that.setData({
          aaaa: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },
  //地区
  bbbb() {
    if (!wx.getStorageSync('userInfo') || !wx.getStorageSync('userInfo').userInfoDetail || !wx.getStorageSync('userInfo').userInfoDetail.nicheng) {
      wx.showToast({
        title: '未填写信息，无法筛选',
        icon: 'none'
      })
      return
    }
    let liss = ['都可以', '仅限老乡', '仅限同城', '老家同省', '工作同省']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];

        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.region1 && item.userInfoDetail.region1[0] == that.data.my_user.region1[0] && item.userInfoDetail.region1[1] == that.data.my_user.region1[1]) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.region1 && item.userInfoDetail.region2[1] == that.data.my_user.region2[1]) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 3) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.region1 && item.userInfoDetail.region1[0] == that.data.my_user.region1[0]) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 4) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.region1 && item.userInfoDetail.region2[0] == that.data.my_user.region2[0]) {
              arr.push(item)
            }
          })
        }
        that.setData({
          bbbb: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },
  //学历
  cccc() {
    let liss = ['都可以', '研究生及以上', '本科及以上', '专科及以下']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];
        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.xuli && item.userInfoDetail.xuli == "研究生及以上") {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.xuli && item.userInfoDetail.xuli == "本科") {
              arr.push(item)
            }
            if (item.userInfoDetail && item.userInfoDetail.xuli && item.userInfoDetail.xuli == "研究生及以上") {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 3) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.xuli && item.userInfoDetail.xuli == "专科及以下") {
              arr.push(item)
            }
          })
        }
        that.setData({
          cccc: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },
  //身高
  dddd() {
    if (!wx.getStorageSync('userInfo') || !wx.getStorageSync('userInfo').userInfoDetail || !wx.getStorageSync('userInfo').userInfoDetail.nicheng) {
      wx.showToast({
        title: '未填写信息，无法筛选',
        icon: 'none'
      })
      return
    }
    let liss = ['都可以', '比我高', '比我矮']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];
        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.shengao && item.userInfoDetail.shengao > that.data.my_user.shengao) {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.shengao && item.userInfoDetail.shengao < that.data.my_user.shengao) {
              arr.push(item)
            }
          })
        }
        that.setData({
          dddd: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },
  //车房
  eeee() {
    let liss = ['都可以', '有车有房', '有车没房', '有房没车', '没车没房']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];
        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {

          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.car && item.userInfoDetail.house) {

              if (item.userInfoDetail.car.substr(-2) + item.userInfoDetail.house.substr(-2) == "有车有房") {
                arr.push(item)
              }
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.car && item.userInfoDetail.house) {
              if (item.userInfoDetail.car.substr(-2) + item.userInfoDetail.house.substr(-2) == "有车没房") {
                arr.push(item)
              }
            }
          })
        } else if (res.tapIndex == 3) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.car && item.userInfoDetail.house) {
              if (item.userInfoDetail.house.substr(-2) + item.userInfoDetail.car.substr(-2) == "有房没车") {
                arr.push(item)
              }
            }
          })
        } else if (res.tapIndex == 4) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.car && item.userInfoDetail.house) {
              if (item.userInfoDetail.car.substr(-2) + item.userInfoDetail.house.substr(-2) == "没车没房") {
                arr.push(item)
              }
            }
          })
        }
        console.log('筛选车房', liss[res.tapIndex], arr)
        that.setData({
          eeee: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },
  //职业
  ffff() {
    let liss = ['都可以', '企业员工', '公务员', '自由职业', '其他']
    wx.showActionSheet({
      itemList: liss,
      itemColor: '',
      success: function (res) {
        var list = that.data.yuan_list
        var arr = [];
        if (res.tapIndex == 0) {
          arr = list
        } else if (res.tapIndex == 1) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.ziyie && item.userInfoDetail.ziyie == "企业员工") {
              arr.push(item)
            }
          })
        } else if (res.tapIndex == 2) {
          list.forEach(item => {
            if (item.userInfoDetail && item.userInfoDetail.ziyie && item.userInfoDetail.ziyie == "公务员") {
              arr.push(item)
            }
          })
        } else {
          arr = list
        }
        that.setData({
          ffff: liss[res.tapIndex]
        })
        that.set_vv_data(arr)
      }
    })
  },



  saixuan_nianling() {
    let userInfoDetail = wx.getStorageSync('userInfo').userInfoDetail
    let data = {
      age: userInfoDetail.age
    }
    // 年龄
    if (this.data.aaaa == '相差5岁以内') {
      data.age = userInfoDetail.age - 5 < age < userInfoDetail.age + 5
    }
    if (this.data.aaaa == '比我大') {
      data.age = age < userInfoDetail.age
    }
    if (this.data.aaaa == '比我小') {
      data.age = age > userInfoDetail.age
    }
    // 学历
    if (this.data.aaaa == '相差5岁以内') {
      data.age = userInfoDetail.age - 5 < age < userInfoDetail.age + 5
    }
    console.log('筛选', data)

  },
  onShareAppMessage: function (res) {
    if (res.from == 'button') {
      return {
        path: "/pages/user_detail/user_detail?openid=" + wx.getStorageSync('userInfo')._openid + '&share=true',
        success: function (e) {},
        // title: getApp().share_title || null,
        imageUrl: wx.getStorageSync('userInfo').userInfoDetail.live_phone[0]
      }
    }
  },
})